/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.develop;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.mapper.query.NativeQuery;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.rpc.SystemSettingRpcService;
import com.je.ibatis.extension.plugins.pagination.Page;
import com.je.rbac.annotation.ControllerAuditLog;
import com.je.rbac.rpc.MetaRbacRpcServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/je/meta/devManagement")
public class DevelopManagementController extends AbstractPlatformController {

    private static final String PK_ID = "18818cbc40574fd99714b59368ea7acf";
    private static final String TABLE_CODE = "JE_META_KFTDGL";

    @Autowired
    private MetaRbacRpcServiceImpl metaRbacRpcService;
    @Autowired
    private SystemSettingRpcService systemSettingRpcService;

    @Override
    @RequestMapping(value = "/load", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "开发团队模块",operateTypeCode = "loadDevelopTeam",operateTypeName = "查看开发团队",logTypeCode = "systemManage",logTypeName = "系统管理")
    public BaseRespResult load(BaseMethodArgument param, HttpServletRequest request) {

        String devManagerIds = systemSettingRpcService.findSettingValue("JE_SYS_DEVMANAGER");
        String devManagerNames = systemSettingRpcService.findSettingValue("JE_SYS_DEVMANAGER_NAME");
        String devMemberIds = systemSettingRpcService.findSettingValue("JE_SYS_ADMIN");
        String devMemberNames = systemSettingRpcService.findSettingValue("JE_SYS_ADMIN_NAME");

        DynaBean dynaBean = metaService.selectOneByPk(TABLE_CODE, PK_ID);
        List<DynaBean> devManagerUserIdList = metaRbacRpcService.selectByTableCodeAndNativeQueryWithColumns("JE_RBAC_VUSERQUERY", NativeQuery.build().in("JE_RBAC_ACCOUNTDEPT_ID", Arrays.asList(devManagerIds.split(","))), "USER_ID");
        List<DynaBean> devMemberUserIdList = metaRbacRpcService.selectByTableCodeAndNativeQueryWithColumns("JE_RBAC_VUSERQUERY", NativeQuery.build().in("JE_RBAC_ACCOUNTDEPT_ID", Arrays.asList(devMemberIds.split(","))), "USER_ID");
        String devManagerUserId = devManagerUserIdList.stream().map(a -> a.getStr("USER_ID")).collect(Collectors.joining(","));
        String devMemberUserId = devMemberUserIdList.stream().map(a -> a.getStr("USER_ID")).collect(Collectors.joining(","));

        dynaBean.setStr("KFTDGL_KFZGLY_ID", devManagerIds);
        dynaBean.setStr("KFTDGL_KFZGLY_NAME", devManagerNames);
        dynaBean.setStr("KFTDGL_KFZGLYYH_ID", devManagerUserId);
        dynaBean.setStr("KFTDGL_KFTDCY_ID", devMemberIds);
        dynaBean.setStr("KFTDGL_KFTDCY_NAME", devMemberNames);
        dynaBean.setStr("KFTDGL_KFTDCYYH_ID", devMemberUserId);
        metaService.update(dynaBean);
        List<HashMap<String, Object>> list = new ArrayList<>();
        list.add(dynaBean.getValues());
        Page page = new Page(1, 30);
        page.setRecords(list);

        return BaseRespResult.successResultPage(page.getRecords(), (long) page.getTotal());
    }

    @Override
    @RequestMapping(value = "/doUpdateList", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "开发团队模块",operateTypeCode = "updateDevelopTeamList",operateTypeName = "更新开发团队集合",logTypeCode = "systemManage",logTypeName = "系统管理")
    public BaseRespResult doUpdateList(BaseMethodArgument param, HttpServletRequest request) {

        try {
            String strData = getStringParameter(request, "strData");
            if (!Strings.isNullOrEmpty(strData)) {
                JSONArray jsonArray = JSONArray.parseArray(strData);
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                    String devManagerIds = jsonObject.get("KFTDGL_KFZGLY_ID") == null ? "" : jsonObject.get("KFTDGL_KFZGLY_ID").toString();
                    String devManagerNames = jsonObject.get("KFTDGL_KFZGLY_NAME") == null ? "" : jsonObject.get("KFTDGL_KFZGLY_NAME").toString();
                    String devMemberIds = jsonObject.get("KFTDGL_KFTDCY_ID") == null ? "" : jsonObject.get("KFTDGL_KFTDCY_ID").toString();
                    String devMemberNames = jsonObject.get("KFTDGL_KFTDCY_NAME") == null ? "" : jsonObject.get("KFTDGL_KFTDCY_NAME").toString();
                    if (!Strings.isNullOrEmpty(devManagerIds)) {
                        metaService.executeSql("update je_core_setting set VALUE = '" + devManagerIds + "' where CODE = 'JE_SYS_DEVMANAGER'");
                        metaService.executeSql("update je_core_setting set VALUE = '" + devManagerNames + "' where CODE = 'JE_SYS_DEVMANAGER_NAME'");
                    }
                    if (!Strings.isNullOrEmpty(devMemberIds)) {
                        metaService.executeSql("update je_core_setting set VALUE = '" + devMemberIds + "' where CODE = 'JE_SYS_ADMIN'");
                        metaService.executeSql("update je_core_setting set VALUE = '" + devMemberNames + "' where CODE = 'JE_SYS_ADMIN_NAME'");
                    }
                }

            }

            return super.doUpdateList(param, request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "开发团队模块",operateTypeCode = "updateDevelopTeam",operateTypeName = "更新开发团队",logTypeCode = "systemManage",logTypeName = "系统管理")
    public BaseRespResult doUpdate(BaseMethodArgument param, HttpServletRequest request) {

        try {
            String devManagerIds = getStringParameter(request, "KFTDGL_KFZGLY_ID");
            String devManagerNames = getStringParameter(request, "KFTDGL_KFZGLY_NAME");
            String devMemberIds = getStringParameter(request, "KFTDGL_KFTDCY_ID");
            String devMemberNames = getStringParameter(request, "KFTDGL_KFTDCY_NAME");

            if (!Strings.isNullOrEmpty(devManagerIds)) {
                metaService.executeSql("update je_core_setting set VALUE = '" + devManagerIds + "' where CODE = 'JE_SYS_DEVMANAGER'");
                metaService.executeSql("update je_core_setting set VALUE = '" + devManagerNames + "' where CODE = 'JE_SYS_DEVMANAGER_NAME'");
            }
            if (!Strings.isNullOrEmpty(devMemberIds)) {
                metaService.executeSql("update je_core_setting set VALUE = '" + devMemberIds + "' where CODE = 'JE_SYS_ADMIN'");
                metaService.executeSql("update je_core_setting set VALUE = '" + devMemberNames + "' where CODE = 'JE_SYS_ADMIN_NAME'");
            }
            return super.doUpdate(param, request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
